package com.jd.service.impl;

import com.jd.bo.UserBO;
import com.jd.enums.Sex;
import com.jd.mapper.StuMapper;
import com.jd.mapper.UserMapper;
import com.jd.pojo.Stu;
import com.jd.pojo.User;
import com.jd.service.StuService;
import com.jd.service.UserService;
import com.jd.utils.DateUtil;
import com.jd.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //默认用户头像
    private static  final String USER_FACE="";


    @Autowired
    private Sid sid;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Example userExample=new Example(User.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("username",username);
        User result=userMapper.selectOneByExample(userExample);
        return result==null?false:true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public User createUser(UserBO userBO) {
        String userId=sid.nextShort();
        User user=new User();
        user.setId(userId);
        user.setUsername(userBO.getUsername());
        try {
            user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //默认用户昵称通用户名
        user.setNickname(user.getUsername());
        //默认头像
        user.setFace(USER_FACE);
        user.setBirthday(DateUtil.stringToDate("1900-01-01"));
        user.setSex(Sex.secret.type);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        userMapper.insert(user);
        return user;
    }

    @Override
    public User queryUserForLogin(String username, String password) {
        Example userExample=new Example(User.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("username",username);
        userCriteria.andEqualTo("password",password);
        User result=userMapper.selectOneByExample(userExample);
        return result;
    }
}